package top.meijhm.communitymanagement.common.auth.model;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import top.meijhm.communitymanagement.user.model.User;
import top.meijhm.communitymanagement.user.service.UserService;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getUserByName(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        return new UserDetailsImpl(user.getId(), user.getUsername(), user.getPassword(), getUserAuthority(user.getId()));
    }

    /**
     * 获取用户权限信息
     *
     * @param id 用户id
     * @return List<GrantedAuthority> 用户权限列表
     */
    public List<GrantedAuthority> getUserAuthority(Long id) {
        // 实际怎么写以数据表结构为准，这里只是写个例子
        // 角色，比如ROLE_ADMIN，ROLE_USER
        String authority = userService.getUserById(id).getUserRole().name();
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}